<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="课程方向" prop="courseId">
        <el-select v-model="queryParams.courseId" placeholder="请选择课程" clearable @change="changeQueryCourse">
          <el-option v-for="item in courseSelectList" :key="item.courseId" :label="item.courseName"
            :value="item.courseId" />
        </el-select>
      </el-form-item>
      <el-form-item label="班级" prop="classId">
        <el-select v-model="queryParams.classId" placeholder="请选择课程后再选择班级" clearable>
          <el-option v-for="dict in classList" :key="dict.classId" :label="dict.className" :value="dict.classId" />
        </el-select>
      </el-form-item>
      <el-form-item label="学员名称" prop="userName">
        <el-input v-model="queryParams.userName" placeholder="请输入学员名称" clearable />
      </el-form-item>
      <el-form-item label="授权状态" prop="empowerStatus">
        <el-select v-model="queryParams.empowerStatus" placeholder="请选择授权状态" clearable>
          <el-option v-for="item in authOptions" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" :disabled="multiple" @click="handleAuth(null)">授权</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDeleteAuth(null)">删除授权</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="couseTimeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="课程方向" align="center" prop="courseName" />
      <el-table-column label="学员名称" align="center" prop="userName" />
      <el-table-column label="报名时间" align="center" prop="applicationTime" />
      <el-table-column label="授权状态" align="center">
        <template #default="scope">
          <span>{{ scope.row.empowerStatus === '0' ? '未授权' : '已授权' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="授权时间" align="center" prop="empowerTime">
        <template #default="scope">
          <span>{{ scope.row.empowerTime || '--' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleAuth(scope.row)">授权</el-button>
          <el-button link type="primary" icon="Delete" :disabled="!scope.row.empowerId"
            @click="handleDeleteAuth(scope.row)">删除授权</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改录播观看对话框 -->
    <el-dialog title="授权" v-model="open" width="500px" append-to-body>
      <el-form ref="couseTimeRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="授权时间" prop="authTime">
          <el-date-picker v-model="authTime" :clearable="false" type="daterange" start-placeholder="开始日期"
            end-placeholder="结束日期" value-format="YYYY-MM-DD" size="default" @change="datePickerChange" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
  
<script setup name="CouseTime">
import { queryEmpowerList, addEmpower, deleteEmpower } from "@/api/shouquan";
import { queryClassByCourseId } from "@/api/register/registerList.js";
import { queryCourseList } from '@/api/home.js'
import { ref } from "vue";
import dayjs from "dayjs";
import { ElMessage } from "element-plus";

const { proxy } = getCurrentInstance();
const courseSelectList = ref([])
const classList = ref([])

const couseTimeList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const multiple = ref(true);
const total = ref(0);
const authTime = ref(null)
let empowerList = []
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    courseId: null,
    classId: null,
    userName: null,
    empowerStatus: null,
  },
  rules: {
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询录播观看列表 */
function getList() {
  loading.value = true;
  queryEmpowerList(queryParams.value).then(response => {
    couseTimeList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}
const getCourseSelectList = async () => {
  try {
    const res = await queryCourseList()
    if (res.code === 200) {
      courseSelectList.value = res.rows
      console.log(res)
    }
    getList()
  } catch (error) {
    proxy.$modal.msgError(error);
  }
}
function changeQueryCourse(courseId) {
  classList.value = []
  data.queryParams.classId = null
  if (courseId) {
    queryClassList(courseId);
  }
}
/** 根据课程id查询班级列表*/
function queryClassList(courseId) {
  queryClassByCourseId({ courseId }).then((response) => {
    if (response.data && response.data.length) {
      classList.value = response.data;
    }
  });
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}
// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => {
    return { courseId: item.courseId, userId: item.userId, empowerId: item.empowerId, }
  });
  multiple.value = !selection.length;
}

/** 添加授权操作 */
function handleAuth(row) {
  console.log("🚀 ~ file: index.vue:152 ~ handleAuth ~ row:", row)
  reset();
  if (row) {
    empowerList = [{ courseId: row.courseId, userId: row.userId }]
    if (row.empowerTime && row.empowerTime !== '') {
      form.value.beginTime = row.empowerTime.substring(0, 10)
      form.value.endTime = row.empowerTime.substring(11, 21)
      authTime.value = [row.empowerTime.substring(0, 10), row.empowerTime.substring(11, 21)]
    } else {
      form.value.beginTime = dayjs().format('YYYY-MM-DD')
      form.value.endTime = dayjs().add(30, 'day').format('YYYY-MM-DD')
      authTime.value = [dayjs().format('YYYY-MM-DD'), dayjs().add(30, 'day').format('YYYY-MM-DD')]
    }
  } else {
    empowerList = ids.value
    form.value.beginTime = dayjs().format('YYYY-MM-DD')
    form.value.endTime = dayjs().add(30, 'day').format('YYYY-MM-DD')
    authTime.value = [dayjs().format('YYYY-MM-DD'), dayjs().add(30, 'day').format('YYYY-MM-DD')]
  }
  open.value = true;
}

/** 添加授权按钮 */
function submitForm() {
  const pp = JSON.parse(JSON.stringify(form.value))
  pp.empowerList = empowerList
  addEmpower(pp).then(response => {
    proxy.$modal.msgSuccess("授权成功");
    open.value = false;
    getList();
  });
}

/** 删除按钮操作 */
function handleDeleteAuth(row) {
  let _empowerIds = null
  if (row) {
    _empowerIds = row.empowerId
  } else {
    const iis = []
    ids.value.forEach(item => {
      if (item.empowerId && item.empowerId !== '') {
        iis.push(item.empowerId)
      }
    });
    _empowerIds = iis.join()
  }
  if (!_empowerIds || _empowerIds === '') {
    ElMessage.error('没有需要删除授权得数据')
    return
  }
  proxy.$modal.confirm('是否确认删除选中数据项授权？').then(function () {
    return deleteEmpower(_empowerIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除授权成功");
  }).catch(() => { });
}
// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    beginTime: '',
    endTime: '',
    empowerList: [],
  };
  authTime.value = null
  proxy.resetForm("couseTimeRef");
}

// 授权状态 0-未授权 1-已授权
const authOptions = [{
  id: '0',
  name: '未授权'
}, {
  id: '1',
  name: '已授权'
},]
const datePickerChange = (date) => {
  if (!date) {
    form.value.beginTime = "";
    form.value.endTime = "";
  } else {
    form.value.beginTime = date[0];
    form.value.endTime = date[1];
  }
};
getCourseSelectList();
</script>